// ID生成器（雪花算法）
package middleware

import (
	"gitee.com/g_night/ay_snowflake/aysnowflake"
	"sync"
)

// key 设置方式 = machine 左移5位配合 dataCenterId
var workerMap sync.Map // map[int]aysnowflake.SnowflakeIdWorker

func GetIdWorker(machineId, dataCenterId int64) (*aysnowflake.SnowflakeIdWorker, error) {
	key := machineId
	key <<= 5
	key += dataCenterId
	// 获取worker
	worker, ok := workerMap.Load(key)
	if ok {
		res := worker.(*aysnowflake.SnowflakeIdWorker)
		return res, nil
	}
	// 不存在就创建并且存入
	newWorker, err := aysnowflake.InitSnowFlake(machineId, dataCenterId)
	if err != nil {
		return nil, err
	}
	rWorker, _ := workerMap.LoadOrStore(key, newWorker)
	res := rWorker.(*aysnowflake.SnowflakeIdWorker)
	return res, nil
}
